const http = require('http'),
      url = require('url'),
      queryString = require('querystring'),
      request = require('request');

async function getData(req){
    return new Promise((resolve,reject)=>{
        try {
            let tmpStr="";
            req.on("data",async (chunk)=>{
                tmpStr+=chunk;
            });
            req.on("end",async ()=>{
                resolve(queryString.parse(tmpStr))
            })
        } catch (error) {
            reject(error)
        }
        
    })
}

async function TransRequest(method='get',url,data){
    return new Promise((resolve,reject)=>{
        request({
            method:method,
            uri:url ,
            headers: {
                "Host":"m.maoyan.com",
                "referer":"http://m.maoyan.com",
                'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Mobile Safari/537.36'
              },
              form:data
        },
        (err,res)=>{
            if(err){
                reject(err);
                return
            }
            resolve(res.request.req.res.body);
        })
    })
}
http.createServer(async (req,res)=>{
    try {
        let location =url.parse(req.url);
        // console.log(location.path);
        if(location.path=="/favicon.ico"){
            res.end()
            return
        }
        if(/ajax/.test(location.path)){
            let apiUrl = location.path.match(/(ajax)(\W|\w)*/)[0];
            let baseUrl="http://m.maoyan.com/";
            let turl = baseUrl+apiUrl;
            
            // 响应options预检
            if(req.headers['access-control-request-method']=="OPTIONS"){
                res.setHeader("Access-Control-Allow-Headers","Content-Type");
                res.setHeader('Access-Control-Allow-Method', 'GET');
                res.setHeader('Access-Control-Allow-Origin', "http://127.0.0.1:8080");
                res.end()
                return
            }
            //响应POST请求
            if(req.headers['access-control-request-method']=="POST"){
                res.setHeader("Access-Control-Allow-Headers","Content-Type");
                res.setHeader('Access-Control-Allow-Method', 'POST');
                res.setHeader('Access-Control-Allow-Origin', "http://localhost:8080");
                res.end("post");
                return
            } 
            let data = await getData(req);
            let TransRes= await TransRequest(req.method,turl,data);   
            res.setHeader("Content-Type","text/html;charset=utf-8");
            res.setHeader("Access-Control-Allow-Origin","*");
            res.setHeader("Access-Control-Allow-Headers","Content-Type");
            res.end(TransRes);
            return
        }
        res.end("hi");
    } catch (error) {
        console.log(error)
        res.end("{msg:error}")
    }
}).listen("8888");

console.log(`listening: http://localhost:8888`)
